'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Card, Row, Col, Input, Button, Tree, Form, Modal, message, Space, Popconfirm, List, Typography, Alert, Table, Spin, Empty } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ExpandOutlined, CompressOutlined, TeamOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import Layout from '@/components/Layout';
import debounce from 'lodash/debounce';
import { fetchSingleEmployee } from '@/lib/user';
import { getAllOtherDepartments, addOtherDepartment, updateOtherDepartment, deleteOtherDepartment } from '@/lib/otherdept';
import {
  updatePosition,
  deletePosition,
  createPosition,
  Position as LibPosition,
  UpdatePositionParams,
  getPositionEmployees,
  DepartmentPersonItem
} from '@/lib/position'
const { Title, Text } = Typography;

// 定义部门接口
interface OtherDepartment {
  other_dept_id: string;
  other_dept_name: string;
  other_dept_number: string;
  other_dept_level: number;
  other_dept_manager_id: string;
  other_dept_manager_name: string;
  other_dept_profile: string;
  other_dept_parent_id?: number;
  positions?: DeptPosition[];
  deptNumber?: string;
}

// 定义树节点类型
interface TreeItem {
  key: string;
  title: React.ReactNode;
  level: number;
  deptNumber: string;
  children?: TreeItem[];
  other_dept_name?: string;
  other_dept_id?: string;
  other_dept_parent_id?: number;
  other_dept_number?: string;
  other_dept_level?: number;
  other_dept_manager_id?: string;
  other_dept_manager_name?: string;
  other_dept_profile?: string;
  positions?: DeptPosition[];
}

// 定义岗位接口
interface DeptPosition {
  positionId: string | number;
  positionName: string;
  positionNumber: string;
  positionProperties: string;
  jobDescription: string;
  person: number;
}

// 定义最近操作类型
interface RecentAction {
  description: string;
  time: string;
}

// 扩展Position接口
interface Position extends LibPosition {
  positionId: string | number;
}

const OtherDeptManagementPage = () => {
  const [departments, setDepartments] = useState<OtherDepartment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [treeItems, setTreeItems] = useState<TreeItem[]>([]);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogTitle, setDialogTitle] = useState('');
  const [formData, setFormData] = useState<Partial<OtherDepartment>>({
    other_dept_id: '',
    other_dept_name: '',
    other_dept_number: '',
    other_dept_level: 1,
    other_dept_manager_id: '',
    other_dept_manager_name: '',
    other_dept_profile: ''
  });
  const [isEditing, setIsEditing] = useState(false);
  const [managerStatus, setManagerStatus] = useState('');
  const [parentDept, setParentDept] = useState<OtherDepartment | null>(null);
  const [selectedDepartment, setSelectedDepartment] = useState<OtherDepartment | null>(null);
  const [search, setSearch] = useState('');
  const [deleteDialogVisible, setDeleteDialogVisible] = useState(false);
  const [deleteData, setDeleteData] = useState<OtherDepartment | null>(null);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [positionsModalVisible, setPositionsModalVisible] = useState(false);
  const [selectedPositions, setSelectedPositions] = useState<DeptPosition[]>([]);
  const [employeesModalVisible, setEmployeesModalVisible] = useState(false);
  const [currentPosition, setCurrentPosition] = useState<DeptPosition | null>(null);
  const [employees, setEmployees] = useState<DepartmentPersonItem[]>([]);
  const [employeesLoading, setEmployeesLoading] = useState(false);
  const [employeesTotal, setEmployeesTotal] = useState(0);
  const [employeesPage, setEmployeesPage] = useState(1);
  const [employeesPageSize, setEmployeesPageSize] = useState(10);
  const [recentActions, setRecentActions] = useState<RecentAction[]>([]);
  
  const [positionModalVisible, setPositionModalVisible] = useState(false);
  const [editingPosition, setEditingPosition] = useState<DeptPosition | null>(null);
  const [positionForm] = Form.useForm();

  const [form] = Form.useForm();
  const treeRef = useRef(null);

  // 修改岗位列表的列定义，添加查看员工按钮
  const positionColumns = [
    {
      title: '岗位编号',
      dataIndex: 'positionNumber',
      key: 'positionNumber',
    },
    {
      title: '岗位名称',
      dataIndex: 'positionName',
      key: 'positionName',
    },
    {
      title: '岗位性质',
      dataIndex: 'positionProperties',
      key: 'positionProperties',
    },
    {
      title: '在岗人数',
      dataIndex: 'person',
      key: 'person',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: DeptPosition) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<TeamOutlined />} 
            size="small"
            onClick={() => handleViewEmployees(record)}
          >
            查看员工
          </Button>
          <Button 
            type="default" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditPosition(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个岗位吗？"
            onConfirm={() => handleDeletePosition(record.positionId)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="default" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 员工列表的列定义
  const employeeColumns = [
    {
      title: '员工工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '入职时间',
      dataIndex: 'onboardingTime',
      key: 'onboardingTime',
      render: (text: string) => {
        // 格式化日期，去掉时间部分
        if (text) {
          const date = new Date(text);
          return date.toLocaleDateString();
        }
        return '-';
      }
    }
  ];

  // 添加记录最近操作的函数
  const addRecentAction = (description: string) => {
    const now = new Date();
    const timeString = now.toLocaleString();
    setRecentActions(prev => [{description, time: timeString}, ...prev.slice(0, 4)]);
  };

  // 修改confirmDelete函数，确保正确显示部门名称
  const confirmDelete = async () => {
    if (!deleteData) return;
    
    // 打印deleteData，用于调试
    console.log('删除的部门数据:', deleteData);
    
    // 确保部门名称存在，如果不存在则使用默认值
    const deptName = deleteData.other_dept_name || '此部门';
    
    // 直接显示连带删除确认对话框，不进行检查
    Modal.confirm({
      title: '删除确认',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除"${deptName}"吗？删除后，该部门下的所有岗位和员工将一并删除。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        await performDelete();
      }
    });
  };
  
  // 执行删除操作
  const performDelete = async () => {
    try {
      await deleteOtherDepartment(Number(deleteData!.other_dept_id));
      message.success('部门删除成功');
      setDeleteDialogVisible(false);
      fetchDepartments();
      addRecentAction(`删除了部门 "${deleteData!.other_dept_name}"`);
    } catch (error: any) {
      message.error('删除部门失败: ' + error.message);
    }
  };

  // 修改handleViewEmployees函数，完善错误处理
  const handleViewEmployees = async (position: DeptPosition) => {
    setCurrentPosition(position);
    setEmployeesModalVisible(true);
    setEmployeesLoading(true);
    
    try {
      // 确保selectedDepartment存在
      if (!selectedDepartment) {
        message.error('请先选择部门');
        setEmployeesLoading(false);
        return;
      }
      
      // 打印请求参数
      console.log('查询岗位员工请求参数:', {
        deptId: selectedDepartment.other_dept_id,
        deptType: 3, // 其他部门固定为3
        positionId: position.positionId,
        page: employeesPage,
        pageSize: employeesPageSize
      });
      
      const response = await getPositionEmployees(
        Number(selectedDepartment.other_dept_id),
        3, // 其他部门固定为3
        Number(position.positionId),
        employeesPage,
        employeesPageSize
      );
      
      // 打印响应数据
      console.log('查询岗位员工响应:', response);
      
      if (response && response.code === 1 && response.data) {
        setEmployees(response.data.row || []);
        setEmployeesTotal(response.data.total || 0);
        
        // 添加最近操作记录
        addRecentAction(`查看了岗位 "${position.positionName}" 的员工列表`);
      } else {
        message.error(response?.msg || '获取岗位员工失败');
      }
    } catch (error: any) {
      console.error('获取岗位员工失败:', error);
      message.error('获取岗位员工失败: ' + (error.message || '未知错误'));
    } finally {
      setEmployeesLoading(false);
    }
  };
  
  // 处理员工分页变化
  const handleEmployeesPageChange = (page: number, pageSize: number) => {
    setEmployeesPage(page);
    setEmployeesPageSize(pageSize);
    
    // 如果当前有选中的岗位，重新加载员工数据
    if (currentPosition) {
      handleViewEmployees(currentPosition);
    }
  };

  useEffect(() => {
    fetchDepartments();
  }, []);

  const fetchDepartments = async () => {
    try {
      setLoading(true);
      const response = await getAllOtherDepartments();
      
      console.log('获取其他部门响应:', response);
      
      if (!response || !response.data) {
        console.error('响应格式错误:', response);
        throw new Error('服务器响应格式错误');
      }

      const { code, msg, data } = response.data;
      console.log('解析后的数据:', { code, msg, data });

      if (!data) {
        setDepartments([]);
        setTreeItems([]);
        setExpandedKeys([]);
        return;
      }

      let departmentData = [];
      if (data.positions) {
        departmentData = [data];
      } else {
        departmentData = Array.isArray(data) ? data : [data];
      }
      
      console.log('处理后的部门数据:', departmentData);
      
      if (departmentData.length === 0) {
        console.log('部门数据为空');
        setDepartments([]);
        setTreeItems([]);
        setExpandedKeys([]);
        return;
      }

      const processedData = departmentData.map(dept => ({
        other_dept_id: dept.otherDeptId || dept.other_dept_id,
        other_dept_name: dept.otherDeptName || dept.other_dept_name,
        other_dept_number: dept.otherDeptNumber || dept.other_dept_number,
        other_dept_level: dept.otherDeptLevel || dept.other_dept_level,
        other_dept_manager_id: dept.otherDeptManagerId || dept.other_dept_manager_id,
        other_dept_manager_name: dept.otherDeptManagerName || dept.other_dept_manager_name,
        other_dept_profile: dept.otherDeptProfile || dept.other_dept_profile,
        other_dept_parent_id: dept.otherDeptParentId || dept.other_dept_parent_id,
        positions: dept.positions || []
      }));

      console.log('标准化后的部门数据:', processedData);

      setDepartments(processedData);
      const treeData = buildTreeItems(processedData);
      console.log('构建的树形数据:', treeData);
      setTreeItems(treeData);
      setExpandedKeys(treeData.map(item => item.key));
      setError(null);
    } catch (err) {
      console.error('获取部门数据出错:', err);
      const errorMessage = err.response?.data?.msg || err.message || '未知错误';
      setError(`获取其他部门信息失败: ${errorMessage}`);
      message.error(`获取其他部门信息失败: ${errorMessage}`);
      setDepartments([]);
      setTreeItems([]);
      setExpandedKeys([]);
    } finally {
      setLoading(false);
    }
  };

  const buildTreeItems = (departments) => {
    const idMap = new Map();
    departments.forEach(dept => idMap.set(dept.other_dept_id, { ...dept, children: [] }));

    const rootItems = [];
    departments.forEach(dept => {
      const node = idMap.get(dept.other_dept_id);
      if (dept.other_dept_level === 1) {
        rootItems.push(node);
      } else if (dept.other_dept_parent_id && idMap.has(dept.other_dept_parent_id)) {
        const parent = idMap.get(dept.other_dept_parent_id);
        parent.children.push(node);
      }
    });

    const formatNode = (node) => ({
      key: node.other_dept_id,
      title: (
        <Space>
          <span>{node.other_dept_name}</span>
          <Button 
            type="link" 
            size="small" 
            onClick={(e) => {
              e.stopPropagation();
              handleViewPositions(node);
            }}
          >
            查看岗位
          </Button>
        </Space>
      ),
      level: node.other_dept_level,
      deptNumber: node.other_dept_number,
      children: node.children.map(formatNode)
    });

    return rootItems.map(formatNode);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const submitData = {
        ...values,
        otherDeptParentId: parentDept ? parentDept.other_dept_id : 0
      };

      if (isEditing) {
        submitData.otherDeptId = formData.other_dept_id;
      }

      console.log('处理后的提交数据:', submitData);

      const isDeptNumberExist = departments.some(
        dept => dept.other_dept_number === submitData.otherDeptNumber && 
        dept.other_dept_id !== submitData.otherDeptId
      );
      
      if (isDeptNumberExist) {
        console.log('部门编号重复:', submitData.otherDeptNumber);
        message.error('部门编号已存在，请使用其他编号');
        return;
      }

      const response = isEditing
        ? await updateOtherDepartment(submitData)
        : await addOtherDepartment(submitData);
      
      console.log('提交响应:', response);

      if (response.data && response.data.code === 1) {
        message.success(isEditing ? '部门更新成功' : '部门添加成功');
        setDialogVisible(false);
        await fetchDepartments();
      } else {
        throw new Error(response.data.msg || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交部门信息失败：' + (error.response?.data?.msg || error.message));
    }
  };

  const handleNodeClick = async (selectedKeys, info) => {
    const foundDepartment = departments.find(dept => dept.other_dept_id === info.node.key);
    
    if (foundDepartment) {
      setSelectedDepartment({ ...foundDepartment });
      
      if (foundDepartment.other_dept_manager_id && !foundDepartment.other_dept_manager_name) {
        try {
          const response = await fetchSingleEmployee(foundDepartment.other_dept_manager_id);
          if (response.data && response.data.code === 1 && response.data.data) {
            setSelectedDepartment(prev => ({
              ...prev,
              other_dept_manager_name: response.data.data.username || '未知'
            }));
          }
        } catch (err) {
          setSelectedDepartment(prev => ({
            ...prev,
            other_dept_manager_name: '获取失败'
          }));
        }
      }
    } else {
      setSelectedDepartment(null);
    }
  };

  const filteredTreeItems = React.useMemo(() => {
    if (!search) return treeItems;

    const filterTree = (nodes) => {
      return nodes.filter(node => {
        const matchNode = node.title.toLowerCase().includes(search.toLowerCase());
        const children = node.children ? filterTree(node.children) : [];
        if (children.length) node.children = children;
        return matchNode || children.length > 0;
      });
    };

    return filterTree([...treeItems]);
  }, [treeItems, search]);

  const showAddDeptDialog = (parentData = null) => {
    setParentDept(parentData);
    const newFormData = {
      other_dept_id: '',
      other_dept_name: '',
      other_dept_number: parentData ? `${parentData.deptNumber}-` : '',
      other_dept_level: parentData ? parentData.level + 1 : 1,
      other_dept_manager_id: '',
      other_dept_manager_name: '',
      other_dept_profile: ''
    };
    setFormData(newFormData);
    setDialogTitle(parentData ? '添加子部门' : '添加根部门');
    setDialogVisible(true);
    setIsEditing(false);
    setManagerStatus('');
    form.setFieldsValue({
      otherDeptName: '',
      otherDeptNumber: parentData ? `${parentData.deptNumber}-` : '',
      otherDeptLevel: parentData ? parentData.level + 1 : 1,
      otherDeptManagerId: '',
      otherDeptManagerName: '',
      otherDeptProfile: ''
    });
  };

  const handleEdit = async (data: TreeItem) => {
    const selectedDept = departments.find(dept => dept.other_dept_id === data.key) || {
      other_dept_id: '',
      other_dept_name: '',
      other_dept_number: '',
      other_dept_level: 1,
      other_dept_manager_id: '',
      other_dept_manager_name: '',
      other_dept_profile: '',
      other_dept_parent_id: 0
    };
    
    const parentDeptId = selectedDept.other_dept_parent_id;
    const parentDept = parentDeptId && parentDeptId !== 0 
      ? departments.find(dept => dept.other_dept_id === String(parentDeptId)) 
      : null;
    
    setFormData({ 
      ...selectedDept,
      other_dept_parent_id: parentDeptId || 0 
    });
    
    setParentDept(parentDept);
    setDialogTitle('编辑部门');
    setDialogVisible(true);
    setIsEditing(true);
    setManagerStatus('');
    
    form.setFieldsValue({
      otherDeptName: selectedDept.other_dept_name,
      otherDeptNumber: selectedDept.other_dept_number,
      otherDeptLevel: selectedDept.other_dept_level,
      otherDeptManagerId: selectedDept.other_dept_manager_id,
      otherDeptManagerName: selectedDept.other_dept_manager_name,
      otherDeptProfile: selectedDept.other_dept_profile,
      otherDeptParentId: parentDeptId || 0
    });
    
    if (selectedDept.other_dept_manager_id) {
      await fetchManagerName(selectedDept.other_dept_manager_id);
    }
  };

  // 修改handleDelete函数，确保正确设置deleteData
  const handleDelete = (data) => {
    // 打印data，用于调试
    console.log('要删除的部门数据:', data);
    
    // 如果data是树节点，需要找到对应的部门数据
    if (data.key && !data.other_dept_id) {
      const foundDepartment = departments.find(dept => dept.other_dept_id === data.key);
      if (foundDepartment) {
        setDeleteData(foundDepartment);
      } else {
        // 如果找不到对应的部门数据，使用原始数据
        setDeleteData(data);
      }
    } else {
      // 直接使用传入的数据
      setDeleteData(data);
    }
    
    setDeleteDialogVisible(true);
  };

  const onManagerIdInput = async (value) => {
    if (!value) {
      form.setFieldsValue({ otherDeptManagerName: '' });
      setManagerStatus('');
      return;
    }
    try {
      const response = await fetchSingleEmployee(value);
      if (response.data && response.data.code === 1 && response.data.data) {
        const managerName = response.data.data.username || '未知';
        form.setFieldsValue({ otherDeptManagerName: managerName });
        setManagerStatus('found');
      } else {
        form.setFieldsValue({ otherDeptManagerName: '' });
        setManagerStatus('not-found');
      }
    } catch (err) {
      form.setFieldsValue({ otherDeptManagerName: '' });
      setManagerStatus('error');
    }
  };

  const fetchManagerName = async (managerId) => {
    if (!managerId) {
      form.setFieldsValue({ otherDeptManagerName: '' });
      setManagerStatus('');
      return;
    }
    try {
      const response = await fetchSingleEmployee(managerId);
      if (response.data && response.data.code === 1 && response.data.data) {
        const managerName = response.data.data.username || '未知';
        form.setFieldsValue({ otherDeptManagerName: managerName });
        setManagerStatus('found');
      } else {
        form.setFieldsValue({ otherDeptManagerName: '' });
        setManagerStatus('not-found');
      }
    } catch (err) {
      form.setFieldsValue({ otherDeptManagerName: '' });
      setManagerStatus('error');
    }
  };

  const handleViewPositions = (dept) => {
    console.log('查看部门岗位:', {
      部门名称: dept.other_dept_name,
      部门ID: dept.other_dept_id,
      岗位列表: dept.positions
    });
    setSelectedDepartment(dept);
    setSelectedPositions(dept.positions || []);
    setPositionsModalVisible(true);
  };

  const handleAddPosition = () => {
    setEditingPosition(null);
    positionForm.resetFields();
    setPositionModalVisible(true);
  };

  const handleEditPosition = (position) => {
    setEditingPosition(position);
    positionForm.setFieldsValue(position);
    setPositionModalVisible(true);
  };

  const handleDeletePosition = async (positionId: string | number) => {
    try {
      await deletePosition(String(positionId));
      message.success('删除成功');
      // 刷新岗位列表
      if (selectedDepartment) {
        const response = await getAllOtherDepartments();
        const { data } = response.data;
        const deptList = Array.isArray(data) ? data : [data];
        const updatedDept = deptList.find(dept => (dept.otherDeptId || dept.other_dept_id) === selectedDepartment.other_dept_id);
        setSelectedPositions(updatedDept ? (updatedDept.positions || []) : []);
      }
    } catch (error) {
      console.error('删除岗位失败:', error);
      Modal.error({
        title: '删除失败',
        content: error instanceof Error ? error.message : '未知错误'
      });
    }
  };

  const handlePositionSubmit = async () => {
    try {
      const values = await positionForm.validateFields();
      const positionData = {
        ...values,
        deptId: selectedDepartment.other_dept_id,
        deptType: 1
      };
      if (editingPosition) {
        await updatePosition({
          ...positionData,
          positionId: editingPosition.positionId
        });
        message.success('岗位更新成功');
      } else {
        await createPosition(positionData);
        message.success('岗位添加成功');
      }
      setPositionModalVisible(false);
      const response = await getAllOtherDepartments();
      console.log(response)
      const { data } = response.data;
      const deptList = Array.isArray(data) ? data : [data];
      const updatedDept = deptList.find(dept => (dept.otherDeptId || dept.other_dept_id) === selectedDepartment.other_dept_id);
      setSelectedPositions(updatedDept ? (updatedDept.positions || []) : []);
    } catch (error: any) {
      message.error('操作失败：' + error.message);
    }
  };

  return (
    <Layout>
      <Card title="其它部门管理" className="department-management-wrapper">
        <Row gutter={24}>
          <Col span={6}>
            <Card title="部门详情">
              {selectedDepartment && (
                <List>
                  <List.Item>
                    <Text>部门名称：</Text>
                    <Text strong>{selectedDepartment.other_dept_name}</Text>
                  </List.Item>
                  <List.Item>
                    <Text>部门编号：</Text>
                    <Text strong>{selectedDepartment.other_dept_number}</Text>
                  </List.Item>
                  <List.Item>
                    <Text>部门级别：</Text>
                    <Text strong>{selectedDepartment.other_dept_level}</Text>
                  </List.Item>
                  <List.Item>
                    <Text>部门主管ID：</Text>
                    <Text strong>{selectedDepartment.other_dept_manager_id}</Text>
                  </List.Item>
                  <List.Item>
                    <Text>部门主管姓名：</Text>
                    <Text strong>{selectedDepartment.other_dept_manager_name}</Text>
                  </List.Item>
                  <List.Item>
                    <Text>部门描述：</Text>
                    <Text strong>{selectedDepartment.other_dept_profile}</Text>
                  </List.Item>
                </List>
              )}
            </Card>
          </Col>
          <Col span={18}>
            <Card title="部门列表">
              <Input
                placeholder="搜索部门"
                prefix={<SearchOutlined />}
                value={search}
                onChange={e => setSearch(e.target.value)}
                style={{ marginBottom: 16 }}
              />
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={() => showAddDeptDialog()}
                style={{ marginBottom: 16, marginRight: 16 }}
              >
                添加根部门
              </Button>
              {loading ? (
                <div>加载中...</div>
              ) : error ? (
                <Alert message={error} type="error" />
              ) : filteredTreeItems.length === 0 ? (
                <Alert message="没有可用的部门" type="info" />
              ) : (
                <Tree
                  ref={treeRef}
                  treeData={filteredTreeItems}
                  onSelect={handleNodeClick}
                  expandedKeys={expandedKeys}
                  onExpand={(keys: string[]) => setExpandedKeys(keys)}
                  titleRender={(nodeData: TreeItem) => (
                    <Space>
                      <span>{nodeData.title}</span>
                      <Space>
                        <Button 
                          size="small" 
                          icon={<PlusOutlined />} 
                          onClick={(e) => { 
                            e.stopPropagation(); 
                            showAddDeptDialog(nodeData); 
                            handleViewPositions(nodeData);
                          }} 
                        />
                        <Button 
                          size="small" 
                          icon={<EditOutlined />} 
                          onClick={(e) => { 
                            e.stopPropagation(); 
                            handleEdit(nodeData); 
                          }} 
                        />
                        <Popconfirm
                          title="确定要删除这个部门吗？"
                          onConfirm={(e) => { 
                            e.stopPropagation(); 
                            handleDelete(nodeData); 
                          }}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button 
                            size="small" 
                            icon={<DeleteOutlined />} 
                            onClick={(e) => e.stopPropagation()} 
                          />
                        </Popconfirm>
                      </Space>
                    </Space>
                  )}
                />
              )}
            </Card>
          </Col>
        </Row>

        <Modal
          title={dialogTitle}
          open={dialogVisible}
          onOk={handleSubmit}
          onCancel={() => setDialogVisible(false)}
        >
          <Form form={form} layout="vertical" initialValues={formData}>
            <Form.Item 
              name="otherDeptName" 
              label="部门名称" 
              rules={[{ required: true, message: '请输入部门名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item 
              name="otherDeptNumber" 
              label="部门编号" 
              rules={[
                { required: true, message: '请输入部门编号' },
                () => ({
                  validator(_, value) {
                    if (!parentDept || value.startsWith(parentDept.deptNumber)) {
                      return Promise.resolve();
                    }
                    return Promise.reject(
                      new Error(`部门编号必须以父部门编号 ${parentDept.deptNumber} 开头`)
                    );
                  },
                }),
              ]}
            >
              <Input 
                disabled={isEditing} 
                placeholder={
                  parentDept 
                    ? `请输入以 ${parentDept.deptNumber} 开头的编号` 
                    : '请输入部门编号'
                } 
              />
            </Form.Item>
            <Form.Item name="otherDeptLevel" label="部门级别">
              <Input disabled />
            </Form.Item>
            <Form.Item 
              name="otherDeptManagerId" 
              label="部门主管ID" 
              rules={[{ required: true, message: '请输入部门主管ID' }]}
            >
              <Input onChange={(e) => onManagerIdInput(e.target.value)} />
            </Form.Item>
            <Form.Item name="otherDeptManagerName" label="部门主管姓名">
              <Input disabled />
            </Form.Item>
            <Form.Item 
              name="otherDeptProfile" 
              label="部门描述" 
              rules={[{ required: true, message: '请输入部门描述' }]}
            >
              <Input.TextArea />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="删除确认"
          open={deleteDialogVisible}
          onOk={confirmDelete}
          onCancel={() => setDeleteDialogVisible(false)}
          okText="确认"
          cancelText="取消"
        >
          <p>确定要删除 {deleteData?.other_dept_name} 吗？</p>
        </Modal>

        <Modal
          title="岗位列表"
          open={positionsModalVisible}
          onCancel={() => setPositionsModalVisible(false)}
          footer={[
            <Button key="add" type="primary" onClick={handleAddPosition}>添加岗位</Button>,
            <Button key="close" onClick={() => setPositionsModalVisible(false)}>关闭</Button>
          ]}
          width={1000}
        >
          <Table
            columns={positionColumns}
            dataSource={selectedPositions}
            rowKey="positionId"
            pagination={false}
          />
        </Modal>
        
        <Modal
          title={editingPosition ? '编辑岗位' : '添加岗位'}
          open={positionModalVisible}
          onCancel={() => setPositionModalVisible(false)}
          onOk={handlePositionSubmit}
        >
          <Form form={positionForm} layout="vertical">
            <Form.Item
              name="positionNumber"
              label="岗位编号"
              rules={[{ required: true, message: '请输入岗位编号' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="positionName"
              label="岗位名称"
              rules={[{ required: true, message: '请输入岗位名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="positionProperties"
              label="岗位性质"
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="jobDescription"
              label="岗位描述"
            >
              <Input.TextArea />
            </Form.Item>
            <Form.Item
              name="person"
              label="在岗人数"
              rules={[{ required: true, message: '请输入在岗人数' }]}
            >
              <Input type="number" />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title={currentPosition ? `${currentPosition.positionName} 岗位员工` : '岗位员工'}
          open={employeesModalVisible}
          onCancel={() => setEmployeesModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setEmployeesModalVisible(false)}>
              关闭
            </Button>
          ]}
          width={800}
        >
          {employeesLoading ? (
            <div style={{ textAlign: 'center', padding: '30px' }}>
              <Spin tip="加载中..." />
            </div>
          ) : employees.length > 0 ? (
            <Table
              columns={employeeColumns}
              dataSource={employees}
              rowKey="employeeId"
              pagination={{
                current: employeesPage,
                pageSize: employeesPageSize,
                total: employeesTotal,
                onChange: handleEmployeesPageChange,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          ) : (
            <Empty description="暂无员工数据" />
          )}
        </Modal>

      </Card>
    </Layout>
  );
};

export default OtherDeptManagementPage;